﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Xml;

namespace Easyleave.Logic.Membership
{
    /// <summary>
    /// Access information of the recommendation hierachy required for leave approval. 
    /// This information will generally come from an external system.
    /// </summary>
    public class RecommenderHierachy
    {
        /// <summary>
        /// Get the next person in the recommendation hierachy for this user
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="currentRecommenderId"></param>
        /// <returns></returns>
        public static Guid GetNextRecommender(Guid? userId, Guid? currentRecommenderId)
        {
            // load the xml
            XmlDocument doc = Util.GetMemebershipXml();

            // get next recommender order
            int nextRecommenderOrder = 1;
            if (Guid.Empty != currentRecommenderId)
            {
                string xpath1 = string.Format("/users/user[@id='{0}']/managers/recommender[@id='{1}']/@order", new string[] { userId.ToString().ToUpper(), currentRecommenderId.ToString().ToUpper() });
                XmlNode currentOrderAtt = doc.SelectSingleNode(xpath1);
                if (currentOrderAtt == null) return Guid.Empty;
                nextRecommenderOrder = int.Parse(((XmlAttribute)currentOrderAtt).Value) + 1;
            }

            //get next recommender id
            string xpath2 = string.Format("/users/user[@id='{0}']/managers/recommender[@order='{1}']/@id", new string[] { userId.ToString().ToUpper(), nextRecommenderOrder.ToString() });
            XmlNode nextRecommender = doc.SelectSingleNode(xpath2);
            if (nextRecommender == null) return Guid.Empty;
            return new Guid(((XmlAttribute)nextRecommender).Value);
        }

        /// <summary>
        /// Get the person who will approve/reject the leave
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static Guid GetApprover(Guid? userId)
        {
            XmlDocument doc = Util.GetMemebershipXml();
            string xpath2 = string.Format("/users/user[@id='{0}']/managers/approver/@id", new string[] { userId.ToString().ToUpper()});
            XmlNode approver = doc.SelectSingleNode(xpath2);
            if (approver == null) return Guid.Empty;
            return new Guid(((XmlAttribute)approver).Value);
        }
    }
}
